package com.wyc.apidriver.interceptor;

import com.wyc.internalCommon.constant.TokenContant;
import com.wyc.internalCommon.result.ApiResult;
import com.wyc.internalCommon.result.TokenResult;
import com.wyc.internalCommon.util.JWTUtils;
import com.wyc.internalCommon.util.RedisKeyUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * token拦截器
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result = true;
        String resultString = "";

        String requestToken = request.getHeader("Authorization");

        TokenResult tokenResult = JWTUtils.checkToken(requestToken);
        if (null == tokenResult){
            resultString = "success token invalid";
            result = false;
        }else {
            // 校验token
            String tokenKey = RedisKeyUtils.generatorTokenKeyByPhoneWithId(tokenResult.getPhone(),tokenResult.getIdentity(), TokenContant.SUCCESS_TOKEN_TYPE);
            String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);
            if (!StringUtils.hasLength(redisToken) || !requestToken.equals(redisToken)){
                resultString = "success token invalid";
                result = false;
            }
        }

        if (!result){
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(ApiResult.error(resultString)).toString());
        }



        return result;
    }
}
